from neo4j import GraphDatabase

def check_all_duplicates():
    driver = GraphDatabase.driver('neo4j://49.235.155.102:7687', auth=('neo4j', '123qweasd!'))
    session = driver.session()
    
    print("=== 检查所有节点类型统计 ===")
    
    # 检查各类型节点数量
    node_types = ['Topic', 'Subtopic', 'KnowledgePoint', 'Concept']
    for node_type in node_types:
        result = session.run(f'MATCH (n:{node_type}) RETURN count(n) as count')
        count = result.single()["count"]
        print(f'{node_type}节点数: {count}')
    
    print("\n=== 检查可能的重复节点名称 ===")
    
    # 检查是否有相同名称的节点存在于不同类型中
    result = session.run("""
        MATCH (n)
        WHERE n.name IS NOT NULL
        WITH n.name as name, collect(DISTINCT labels(n)[0]) as node_types, count(*) as count
        WHERE count > 1
        RETURN name, node_types, count
        ORDER BY count DESC
    """)
    
    duplicates = list(result)
    if duplicates:
        print("发现重复名称的节点:")
        for record in duplicates:
            print(f"  名称: '{record['name']}' 出现在: {record['node_types']} (共{record['count']}个)")
    else:
        print("✅ 没有发现重复名称的节点")
    
    print("\n=== 检查层级关系完整性 ===")
    
    # 检查每个层级的PART_OF关系
    relationships = [
        ('Subtopic', 'Topic'),
        ('KnowledgePoint', 'Subtopic'), 
        ('Concept', 'KnowledgePoint')
    ]
    
    for from_type, to_type in relationships:
        result = session.run(f"""
            MATCH (from:{from_type})-[:PART_OF]->(to:{to_type})
            RETURN count(*) as count
        """)
        count = result.single()["count"]
        print(f'{from_type} -> {to_type} 关系数: {count}')
    
    print("\n=== 检查孤立节点 ===")
    
    # 检查没有PART_OF关系的节点（除了Topic）
    for node_type in ['Subtopic', 'KnowledgePoint', 'Concept']:
        result = session.run(f"""
            MATCH (n:{node_type})
            WHERE NOT (n)-[:PART_OF]->()
            RETURN n.name as name, n.id as id
        """)
        orphans = list(result)
        if orphans:
            print(f"孤立的{node_type}节点:")
            for record in orphans:
                print(f"  {record['name']} (ID: {record['id']})")
        else:
            print(f"✅ 没有孤立的{node_type}节点")
    
    session.close()
    driver.close()

if __name__ == '__main__':
    check_all_duplicates()